<?php
/**
 * Created by PhpStorm.
 * User: jack Wang
 * Date: 2021/10/15
 * Time: 11:20
 */

class Callback extends Base_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Users_model');
        $this->load->service('Jwt_service');
    }

    public function gitCallback()
    {
        //获取当前用户返回的code
        if (empty($_SERVER['QUERY_STRING'])) {
            fail(400, '参数错误');
        }
        $code = $_SERVER['QUERY_STRING'];
        $get_token_url = config_item('gitee_get_token');
        $client_id = config_item('gitee_client_id');
        $redirect_uri = config_item('gitee_redirect_uri');
        $client_secret = config_item('gitee_client_secret');
        $get_info_url = config_item('gitee_get_info');
        //发送curl获取当前用户的token
        $url1 = $get_token_url . '?grant_type=authorization_code&' . $code . '&client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret;
        $res = curl_request($url1);
        $res = json_decode($res, true);
        $token = $res['access_token'];
        //通过token获取用户基本信息
        $url2 = $get_info_url . '?access_token=' . $token;
        $info = curl_request($url2, false);
        $info = json_decode($info, true);
        //通过gitee的id判断该用户gitee账号是否已经注册
        $count = $this->Users_model->checkTrilateralLogin(1, $info['id']);
        $count = $count[0]['num'];
        //使用过gitee三方账号登录
        if (!empty($info['id'])) {
            if ($count > 0) {
                $userInfo = $this->Users_model->TrilateralLogin($info['id']);
                $userInfo[0]['token'] = $this->Jwt_service->getToken($userInfo['id']);
                success($userInfo);
            } else {
                $userInfo = $this->Users_model->TrilateralRegister($info['name'], encrypt(123), 1, $info['id']);
                $userInfo[0]['token'] = $this->Jwt_service->getToken($userInfo['id']);
                success($userInfo);
            }
        }
        fail(400, '信息有误');
    }
}